package mercurius.fitness.client.ui;

import java.util.HashMap;
import java.util.Vector;

import mercurius.fitness.client.Fitness;
import mercurius.fitness.client.util.Entry;
import mercurius.fitness.client.util.HTTPUtil;
import mercurius.fitness.client.util.Logger;
import net.pleso.framework.client.ui.windows.Slider;
import net.pleso.framework.client.ui.windows.Window;
import pl.rmalinowski.gwt2swf.client.ui.SWFParams;
import pl.rmalinowski.gwt2swf.client.ui.SWFWidget;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;


public class SWFFrame extends Window implements WindowResizeListener {

	public SWFFrame(String caption,Entry[] entries) {
		super(null);
		init(caption,entries);
		
	}
	private final SimplePanel p = new SimplePanel();
	private SWFParams params = new SWFParams();
	private HTML link = new HTML("<a href='javascript:;'>Open in new window</a>");
	private VerticalPanel v = new VerticalPanel();
	
	private void init(String caption,final Entry[] entries) {
		this.setCaption(caption);

		p.add(new HTML("Loading ..."));
		
		HTTPUtil.doPost(Fitness.get().getURL(),entries,new RequestCallback() {

			public void onResponseReceived(Request request, Response response) {
				String str = response.getText();
				HashMap props = new HashMap();
				
				if(str.startsWith("{")) {
	  				String results = str;
	  				JSONObject jsonObject = JSONParser.parse(results).isObject();
	  				Object[] keys = jsonObject.keySet().toArray();
	  				for(int i=0;i<keys.length;i++) {
	  					props.put(keys[i],jsonObject.get((String) keys[i]).isString().stringValue());
	  				}
				} else {
					p.clear();
					p.add(new HTML("Error occured, incorrect results."));
					Logger.error("Error occured, incorrect results.");
				}

				if(!props.containsKey("flash_file")) {
					p.clear();
					p.add(new HTML("Error occured, could not find flash_file."));
					Logger.error("Error occured, could not find flash_file.");
				} else {
					setupHTMLFrame(props,entries);
				}
			}

			public void onError(Request request, Throwable exception) {
				p.clear();
				p.add(new HTML("Error occured, check logs"));
				Logger.error("Error occured, check logs.",exception);
			}
		});

		this.initWidget(p);
	}
	
	private void setupHTMLFrame(HashMap props,final Entry[] entries) {
		
		String flashFile = (String) props.get("flash_file");
		
        params.setSrc(flashFile);
         Object[] keys = props.keySet().toArray();
        for(int i=0;i<keys.length;i++) {
        	if(!keys[i].equals("flash_file")) {
        		params.addVar((String) keys[i],(String) props.get(keys[i]));
        	}
        }

		link.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				Vector v = new Vector(entries.length -1);
				for(int i=0;i<entries.length;i++) {
					if(!entries[i].getName().equals("module")) {
						v.add(entries[i]);
					}
				}
				v.add(new Entry("fulldisplay","true"));
				Fitness.open(Fitness.get().getURL()+"?"+HTTPUtil.buildQueryString(v.toArray()));
			}
		});
		

		
		p.clear();
		p.add(v);
		v.setSpacing(5);
		
		int height = com.google.gwt.user.client.Window.getClientHeight();
		int width = com.google.gwt.user.client.Window.getClientWidth();
		
		onWindowResized(width,height);
		
		// Add a listener for browser resize events.
			com.google.gwt.user.client.Window.addWindowResizeListener(this); 
	}
	
	public SWFFrame(Slider parentSlider,String caption,Entry[] entries) {
		super(parentSlider);
		init(caption,entries);
	}
	

	public void onWindowResized(int width, int height) {
		 height = com.google.gwt.user.client.Window.getClientHeight();
		 width = com.google.gwt.user.client.Window.getClientWidth();
		
		 width = width - 10;
		 height = height - 110;
		
		params.setHeight("100%");
        params.setWidth("100%");

        v.clear();
        v.add(link);
        SimplePanel swfPanel = new SimplePanel();
        swfPanel.setSize(width+"",height+"");
        swfPanel.add(new SWFWidget(params));
        v.add(new HTML("<hr/>"));
        v.setHeight("100%");
        v.setWidth("100%");
        v.add(swfPanel);
        
	}

}
